package com.woniu.consumers;

import com.rabbitmq.client.Channel;
import com.woniu.service.util.Sample;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Component
public class Consumer {
    @Component
    public class SendLoginCodeConsumer {
        @RabbitListener(queues = "sendLoginCodeQueue")
        public void onMsg(Message message, Map<String, String> infoMap, Channel channel) throws Exception {
            sendMessage(infoMap, message, channel);
        }
    }

    @Component
    public class SendRegisterCodeConsumer {
        @RabbitListener(queues = "sendRegisterCodeQueue")
        public void onMsg(Message message, Map<String, String> infoMap, Channel channel) throws Exception {
            sendMessage(infoMap, message, channel);
        }
    }

    @Component
    public class SendForgetPasswordCodeQueue {
        @RabbitListener(queues = "sendForgetPasswordCodeQueue")
        public void onMsg(Message message, Map<String, String> infoMap, Channel channel) throws Exception {
            sendMessage(infoMap, message, channel);
        }
    }

    private boolean sendMessage(Map<String, String> infoMap, Message message, Channel channel) throws Exception {
        try {
            System.out.println(infoMap);
            System.out.println(message);
            System.out.println("接收发送短息的需求 " + new Date());
            Sample.sendCode(infoMap);
            System.out.println("短息发送成功 " + new Date());
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return false;
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        return true;
    }

}
